package com.android.likeweixin.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.android.likeweixin.LikeWeixinApp;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;

public class StringUtily {

	/**
	 * 替换string中表情字符 <功能详细描述>
	 * 
	 * @param s
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public static String resetIMGorFace(String s) {
		if (s != null) {
			if (s.startsWith("_img") || s.startsWith("img_")) {
				return "[图片]";
			}
		}

		// 正则表达式比配字符串里是否含有表情
		String zhengze = "\\[[^\\]]+\\]";
		// 通过传入的正则表达式来生成一个pattern
		Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);
		Matcher matcher = sinaPatten.matcher(s);

		while (matcher.find()) {
			String key = matcher.group();
			String key1 = key.replace("[", "");
			String key2 = key1.replace("]", "");
			// 返回第一个字符的索引的文本匹配整个正则表达式,ture 则继续递归
			int j = matcher.start();
			if (j < 0) {
				continue;
			}
			int imageid;
			imageid = LikeWeixinApp
					.getInstance()
					.getResources()
					.getIdentifier(key2, "drawable",
							LikeWeixinApp.getInstance().getPackageName());
			if (imageid == 0) {
				try {
					imageid = Integer.parseInt(key2);
				} catch (Exception e) {
					continue;
				}
			}
			s = s.replace(String.valueOf(key2), "表情");
		}
		return s;
	}

	public static SpannableString getExpressionString(Context context,
			String biaoqing) {
		SpannableString spannableString = new SpannableString(biaoqing);
		// 正则表达式比配字符串里是否含有表情
		String zhengze = "\\[[^\\]]+\\]";
		// 通过传入的正则表达式来生成一个pattern
		Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);
		Matcher matcher = sinaPatten.matcher(spannableString);

		while (matcher.find()) {
			String key = matcher.group();
			String key1 = key.replace("[", "");
			// 文件名称
			String key2 = key1.replace("]", "");
			// 返回第一个字符的索引的文本匹配整个正则表达式,ture 则继续递归
			int j = matcher.start();
			if (j < 0) {
				continue;
			}
			int imageid;
			Drawable drawable;
			imageid = context.getResources().getIdentifier(key2, "drawable",
					context.getPackageName());
			if (imageid == 0) {
				try {
					imageid = Integer.parseInt(key2);
				} catch (Exception e) {
					continue;
				}
			}
			drawable = context.getResources().getDrawable(imageid);
			float densicy = ResolutionUtily.getDensicy(context);
			int size = (int) (24.0f * densicy);
			drawable.setBounds(0, 0, size, size);
			ImageSpan imageSpan = new ImageSpan(drawable,
					ImageSpan.ALIGN_BOTTOM);

			// 计算该图片名字的长度，也就是要替换的字符串的长度
			int end = j + key.length();
			spannableString.setSpan(imageSpan, j, end,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return spannableString;
	}

	public static String getPureMobile(String mobile) {
		if (mobile != null && mobile.startsWith("+86")) {
			mobile = mobile.substring(3);
		}
		return mobile;
	}
}
